﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class shoppingCar : System.Web.UI.Page
{
    BLL.Business.BookBLL bookBLL = new BLL.Business.BookBLL(); // 数据库查询对象
    BLL.Business.ShoppingCarBLL carBLL = new BLL.Business.ShoppingCarBLL();
    BLL.Business.UserBLL userBLL = new BLL.Business.UserBLL();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            if (!object.Equals(Session["UserName"], null))
            {
                BindDataGrid();
            }
            else
            {
                Response.Redirect("IsLogion.aspx");
            }
        }      
    }
    public void BindDataGrid()
    {
        try
        {       
            int userId = 0;
            userId = GetUserId(Session["UserName"].ToString());

            DataSet ds_car = new DataSet();
            ds_car = carBLL.SelectByUserId(userId);
            if ((ds_car == null) ||
                (ds_car.Tables.Count == 0) ||
                (ds_car.Tables.Count == 1 && ds_car.Tables[0].Rows.Count == 0))
            {
                return;
            }
            else
            {
                DataTable dt = new DataTable();
                float SumPrice = 0;

                dt = GetNewTable(ds_car,ref SumPrice);
                this.ShoppingList.DataSource = dt.DefaultView;
                this.ShoppingList.DataBind();
                this.sumPrice.Text = SumPrice.ToString();
            }        
        }
        catch (Exception ex)
        {
            Response.Write("<script>alert('"+ex.ToString()+"')</script>");
        }
    }
    // 结账(将信息添加到  订单Session)
    protected void Unnamed2_Click(object sender, EventArgs e)
    {
        try
        {
            if (!object.Equals(Session["orderList"], null))
            {
                Session.Remove("orderList");
            }
            Session["orderList"] = new Hashtable();
            Label oLblbookId;
            TextBox oTxtCount;           // 要购买的图书数量
            CheckBox oChkIsChecked;

            for (int i = 0; i < ShoppingList.Rows.Count; i++)
            {
                oLblbookId = (Label)ShoppingList.Rows[i].FindControl("BookId");
                oTxtCount = (TextBox)ShoppingList.Rows[i].FindControl("Count");
                oChkIsChecked = (CheckBox)ShoppingList.Rows[i].FindControl("IsChecked");
                if (oChkIsChecked.Checked == true)
                {
                    int currentCount = 0; // 目前图书总数量
                    currentCount = Int32.Parse( bookBLL.SelectByBookId(Int32.Parse(oLblbookId.Text.ToString())).Tables[0].Rows[0]["Book_Countint"].ToString());
                    if (currentCount < Int32.Parse(oTxtCount.Text.ToString()))
                    {
                        Response.Write("<script>alert('图书编号： " + oLblbookId.Text.ToString() + " 目前库存为 "+currentCount.ToString()+ "!')</script>");
                        return;
                    }
                    ((Hashtable)Session["orderList"]).Add(oLblbookId.Text, oTxtCount.Text);
                }
            }
            if (((Hashtable)Session["orderList"]).Count == 0) { }
            else
            {
                Response.Redirect("oderCheck.aspx");
            }
        }
        catch (Exception ex)
        {
            Response.Write("<script>alert('" + ex.Message.ToString() + "')</script>");
        }
    }
    // 对于DataGrid的操作  删除  重新设置Session并且删除数据库中的ShoppingCar
    protected void ShoppingList_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "deleteBook")
        {
            try
            {
                int bookId = Int32.Parse(e.CommandArgument.ToString());  // 获得选中的商品编号
                if (carBLL.Delete(bookId, Session["UserName"].ToString()))   // 删除购物车信息
                {
                    BindDataGrid();  // 重新绑定
                }
                else
                {
                    Response.Write("<script>alert('删除失败！')</script>");
                }
            }
            catch (Exception ex)
            {
                Response.Write("<script>alert('" + ex.Message.ToString() + "')</script>");
            }
        }
    }
    protected int GetUserId(String UserName)
    {
        DataSet ds_user = new DataSet();

        ds_user = userBLL.SelectByName(UserName);
        if ((ds_user == null) ||
           (ds_user.Tables.Count == 0) ||
           (ds_user.Tables.Count == 1 && ds_user.Tables[0].Rows.Count == 0))
        {
            return -1;
        }
        else
        {
           return  Int32.Parse(ds_user.Tables[0].Rows[0]["User_Idint"].ToString());
        }
    }
    protected DataTable GetNewTable(DataSet ds_car, ref float SumPrice)
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("Book_Idint");    // 图书编号
        dt.Columns.Add("Book_Namestr");  // 书名
        dt.Columns.Add("Book_Price");    // 价格
        dt.Columns.Add("Book_Count");    // 要购买的数量

        try
        {
            DataRow dr;
            foreach (DataRow dr_car in ds_car.Tables[0].Rows)
            {
                dr = dt.NewRow();
                int bookId = Convert.ToInt32(dr_car["Book_Idint"].ToString());       // 商品编号
                int count = Convert.ToInt32(dr_car["Car_Quantityint"].ToString());   // 商品数量

                DataSet ds_book = bookBLL.SelectByBookId(bookId);
                float price = 0;   // 原价
                float Discount = 0;// 折扣 
                price = float.Parse(ds_book.Tables[0].Rows[0]["Book_Priceflo"].ToString());
                Discount = float.Parse(ds_book.Tables[0].Rows[0]["Book_Discountflo"].ToString());

                dr["Book_Idint"] = ds_book.Tables[0].Rows[0]["Book_Idint"].ToString();
                dr["Book_Namestr"] = ds_book.Tables[0].Rows[0]["Book_Namestr"].ToString();
                dr["Book_Price"] = price * Discount;           // 价格=原价*折扣
                dr["Book_Count"] = count;

                dt.Rows.Add(dr);
                SumPrice += price * Discount * count;
            }
            return dt;
        }
        catch 
        {
            return null;
        }
    }
}
